<?php

class CardDealer
{
	private $deck = array();

	private function buildDeck( $players )
	{
		$playerOffset = 2;

		$nPlayers = count( $players );

		$move3 = 1 * ( $nPlayers + $playerOffset );
		$move2 = 2 * ( $nPlayers + $playerOffset );
		$move1 = 3 * ( $nPlayers + $playerOffset );
		$backUp = 1 * ( $nPlayers + $playerOffset );
		$turnLeftAndTurnRight = 3 * ( $nPlayers + $playerOffset );
		$uTurn = 1 * ( $nPlayers + $playerOffset );

		$cardIndex = 0;

		while ( $uTurn > 0 )
		{
			$this->deck[] = $cardIndex++;
			$uTurn--;
		}

		while ( $turnLeftAndTurnRight > 0 )
		{
			$this->deck[] = $cardIndex++;
			$turnLeftAndTurnRight--;
		}

		while ( $backUp > 0 )
		{
			$this->deck[] = $cardIndex++;
			$backUp--;
		}

		while ( $move1 > 0 )
		{
			$this->deck[] = $cardIndex++;
			$move1--;
		}

		while ( $move2 > 0 )
		{
			$this->deck[] = $cardIndex++;
			$move2--;
		}

		while ( $move3 > 0 )
		{
			$this->deck[] = $cardIndex++;
			$move3--;
		}

		foreach ( $players as $player )
		{
			foreach ( explode( ",", $player->robot()->lockedRegisters() ) as $card )
			{
				if ( !empty( $card ) )
				{
					array_splice( $this->deck, $card, 1 );
				}
			}
		}
	}

	private function shuffleDeck()
	{
		for ( $i = 0; $i < count( $this->deck ); $i++ )
		{
			$tempCard = $this->deck[$i];
			$randCard = mt_rand( 0, count($this->deck) - 1 );

			$this->deck[$i] = $this->deck[$randCard];
			$this->deck[$randCard] = $tempCard;
		}
	}

	public function dealCards( $players )
	{
		$playerCards = array();

		$this->buildDeck( $players );
		$this->shuffleDeck();

		foreach ( $players as $player )
		{
			$cards = '';
			for ( $i = 1; $i <= $player->robot()->health() - 1; $i++ )
			{
				$cards .= array_shift( $this->deck );

				if ( $i < $player->robot()->health() - 1)
				{
					$cards .= ",";
				}
			}


			$playerCards[$player->id()] = $cards;
		}

		return $playerCards;
	}
}
